<template>
  <div class="app-container">
    <el-card>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="模型名称">
          <el-input v-model="keyword" placeholder="模型名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="success" @click="handleAdd">新增</el-button>
      <el-divider></el-divider>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          v-for="item in tableColumn"
          :key="item.id"
          :label="item.label"
          :prop="item.prop"
          :width="item.width"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; margin-top: 20px; justify-content: end"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pager.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pager.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      center
      title="修改产品建模"
      :visible.sync="editVisible"
      width="1200px"
      @close="closeEdit"
    >
      <el-form ref="productModelEditRef" :model="editForm" inline>
        <el-form-item label="产品" prop="product" required>
          <el-input
            v-model="editForm.product"
            placeholder="请输入产品"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-input
            v-model="editForm.productModel"
            placeholder="请输入产品"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产品规格">
          <el-input
            v-model="editForm.productSpecification"
            placeholder="请输入产品"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName" required>
          <el-input
            v-model="editForm.modelName"
            placeholder="请输入产品"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" required>
          <el-input
            type="textarea"
            v-model="editForm.remark"
            placeholder="请填写备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择">
          <el-button type="primary" @click="selectMaterial">选择</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table :data="productModelingDetail">
        <el-table-column label="序号">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="物料" width="100px">
          <template slot-scope="scope">
            <div>
              {{ scope.row.material.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <div>
              <el-button
                type="primary"
                @click="editProductModelDetail(scope.$index)"
                >选择</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in productModelingDetailColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        ></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div>
              <el-button
                type="primary"
                @click="addProductModelingDetail(scope.$index, scope.row)"
                >添加</el-button
              >
              <el-button
                type="danger"
                @click="delProductModelingDetail(scope.$index)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="closeEdit">取消</el-button>
          <el-button type="primary" @click="submitEditProductModel"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      center
      title="选择物料档案"
      :visible.sync="materialVisible"
      width="1200px"
    >
      <el-row>
        <el-col :span="4">
          <el-tree
            :data="materialCategoryData"
            :props="{ label: 'name' }"
            @node-click="selectMaterialClass"
          ></el-tree>
        </el-col>
        <el-col :span="20">
          <el-table :data="materialData">
            <el-table-column
              v-for="item in materialColumn"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="primary"
                    @click="selectMaterialInfo(scope.row)"
                    >选择</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      center
      title="添加产品建模"
      :visible.sync="addVisible"
      width="1200px"
      @close="closeAdd"
    >
      <el-form ref="productModelAddRef" :model="addForm" inline>
        <el-form-item label="产品" prop="product" required>
          <el-input
            v-model="addForm.product"
            placeholder="请输入产品"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-input
            v-model="addForm.productModel"
            placeholder="请输入产品"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产品规格">
          <el-input
            v-model="addForm.productSpecification"
            placeholder="请输入产品"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName" required>
          <el-input
            v-model="addForm.modelName"
            placeholder="请输入产品"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" required>
          <el-input
            type="textarea"
            v-model="addForm.remark"
            placeholder="请填写备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择">
          <el-button type="primary" @click="selectMaterial">选择</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table :data="productModelingDetail">
        <el-table-column label="序号">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="物料" width="100px">
          <template slot-scope="scope">
            <div>
              {{ scope.row.material.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <div>
              <el-button
                type="primary"
                @click="editProductModelDetail(scope.$index)"
                >选择</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in productModelingDetailColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        ></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div>
              <el-button
                type="primary"
                @click="addProductModelingDetail(scope.$index, scope.row)"
                >添加</el-button
              >
              <el-button
                type="danger"
                @click="delProductModelingDetail(scope.$index)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="closeAdd">取消</el-button>
          <el-button type="primary" @click="submitAddProductModel"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getProductModelingList, getMaterialCategoryList, getMaterialList, editProductModeling, addProductModeling } from '@/api_zc/mes/product-modeling'
export default {
  data () {
    return {
      tableData: [],  //产品建模列表数据
      tableColumn: [
        {
          label: '编号',
          prop: 'id',
        },
        {
          label: '模型名称',
          prop: 'modelName',
        },
        {
          label: '产品',
          prop: 'product',
        },
        {
          label: '产品型号',
          prop: 'productModel',
        },
        {
          label: '产品规格',
          prop: 'productSpecification',
        },
        {
          label: '产品单位',
          prop: 'productUnit',
        }
      ],  //产品建模表格配置
      editVisible: false, //修改对话框可见性
      addVisible: false,  //添加对话框可见性
      editForm: {
        product: '',
        productModel: '',
        productSpecification: '',
        modelName: '',
        remark: '',
      },  // 修改表单
      addForm: {
        product: '',  //产品
        productModel: '', //产品型号
        productSpecification: '', //规格
        modelName: '',  //模型名称
        remark: ''  //备注
      },  //添加表单
      materialVisible: false, //物料对话框可见性
      materialData: [], //物料列表数据
      materialCategoryData: [], //物料分类数据
      materialCategoryPid: 0, //物料分类id,传0获取全部
      materialColumn: [
        {
          label: "编号",
          prop: 'id'
        },
        {
          label: "物料编号",
          prop: 'code'
        },
        {
          label: "物料名称",
          prop: 'name'
        },
        {
          label: "型号",
          prop: 'model'
        },
        {
          label: "规格",
          prop: 'specification'
        },
        {
          label: "单位",
          prop: 'unit'
        },
        {
          label: "单价",
          prop: 'price'
        },
        {
          label: "类型",
          prop: 'category.name'
        },
        {
          label: "备注",
          prop: 'remark'
        },
      ],  //物料列表配置
      productModelingDetail: [],  //产品建模明细-->选择的物料
      productModelingDetailColumn: [
        {
          label: '型号',
          prop: 'material.model'
        },
        {
          label: '规格',
          prop: 'material.specification'
        },
        {
          label: '单位',
          prop: 'material.unit'
        },
        {
          label: '备注',
          prop: 'material.remark'
        },
      ],  //产品建模明细列表配置
      isAddMaterial: true,  //物料新增或修改
      updateMaterialIndex: 0, //修改物料的序号
      total: 0, //产品建模列表的总数目
      keyword: '',  //模型名称关键字搜索
      pager: {  //页数/每页大小
        page: 1,
        limit: 10
      }
    }
  },
  mounted () {
    // 挂在之前获取产品建模列表数据/物料列表数据/物料分类列表数据
    this.getProudctModelingList()
    this.getMaterialCategoryList()
    this.getMaterialList()
  },
  watch: {
    materialCategoryPid () {
      this.getMaterialList()
    }
  },
  methods: {
    // 获取产品建模/物料/物料分类数据
    async getProudctModelingList () {
      const { data: { content, total } } = await getProductModelingList({ keyword: this.keyword, page: this.pager.page, limit: this.pager.limit })
      this.tableData = content
      this.total = total
    },
    async getMaterialCategoryList () {
      const { data } = await getMaterialCategoryList()  //获取的物料分类数据没有目录这一层，下面套了一层
      this.materialCategoryData = [{
        name: '目录',
        id: 0,
        pid: null,
        children: data
      }]
    },
    async getMaterialList () {
      const { data: { content } } = await getMaterialList({ pid: this.materialCategoryPid, keyword: this.keyword })
      this.materialData = content
    },

    // 分页
    handleSizeChange (val) {
      this.pager.limit = val
      this.getProudctModelingList()
    },
    handleCurrentChange (val) {
      this.pager.page = val
      this.getProudctModelingList()
    },

    // 查询/重置
    onSubmit () {
      this.getProudctModelingList()
    },
    onReset () {
      this.keyword = ''
      this.getProudctModelingList()
    },

    // 物料增删改
    selectMaterial () { //这个选择物料按钮是表单项中的，用于添加物料
      this.materialVisible = true
      this.isAddMaterial = true
    },
    selectMaterialClass ({ id }) {  //切换物料分类id，上面侦听materialCategoryPid变化，重新获取物料列表数据
      this.materialCategoryPid = id
    },
    selectMaterialInfo (row) {  //先判断是修改/删除物料，添加/修改到产品建模明细中，外层还需要套几个字段（createTime，updateTime，productModelId）
      if (this.isAddMaterial) { //添加，往产品明细中push选择的物料数据
        this.productModelingDetail.push({
          material: row,
          createTime: new Date(),
          updateTime: new Date(),
          remark: '',
          productModelId: this.editForm.id
        })
        this.materialVisible = false
      } else {
        this.productModelingDetail.splice(this.updateMaterialIndex, 1, {  //修改,updateMaterialIndex（是下面editProductModelDetail赋值给的）,splice先删除一个再添加一个
          material: row,
          createTime: new Date(),
          updateTime: new Date(),
          remark: '',
          productModelId: this.editForm.id
        })
        this.materialVisible = false
      }
    },
    addProductModelingDetail (index, row) { //添加一条空的产品建模明细
      const data = JSON.parse(JSON.stringify(row))  //这里需要深拷贝
      Object.keys(data).forEach(item => {
        if (item == 'material') {
          Object.keys(data[item]).forEach(i => {
            data[item][i] = ''
          })
        } else {
          data[item] = ''
        }
      })
      this.productModelingDetail.splice(index + 1, 0, data) //新增空数据
    },
    delProductModelingDetail (index) {  //删除产品建模明细
      this.productModelingDetail.splice(index, 1)
    },
    editProductModelDetail (index) {  //修改产品建模明细（选择物料进行修改）
      this.materialVisible = true
      this.isAddMaterial = false  //根据isAddMaterial字段，最后判断是新增/修改物料
      this.updateMaterialIndex = index  //updateMaterialIndex用于splice（start，count，【item，。。。】）修改
    },

    // 修改产品建模
    handleEdit (row) {
      this.productModelingDetail = row.detailList
      this.editVisible = true
      this.editForm = row
    },
    submitEditProductModel () {
      this.$refs.productModelEditRef.validate(async (callback) => {
        if (callback) {
          const { code } = await editProductModeling({ ...this.editForm, detailList: this.productModelingDetail.filter(item => item.material.name) })
          if (code == 200) {
            this.$message.success('修改成功')
            this.editVisible = false
            this.getProudctModelingList()
          } else {
            this.$message.error('物料不能为空，请选择物料！')
          }
        } else {
          this.$message.error('请完善信息')
        }
        this.productModelingDetail = []
      })
    },
    closeEdit () {
      this.$refs.productModelEditRef.resetFields()
      this.getProudctModelingList()
      this.editVisible = false
      this.productModelingDetail = []
    },

    // 新增产品建模
    handleAdd () {
      this.addVisible = true
    },
    submitAddProductModel () {
      this.$refs.productModelAddRef.validate(async (callback) => {
        if (callback) {
          const { code } = await addProductModeling({ ...this.addForm, detailList: this.productModelingDetail.filter(item => item.material.name) })
          if (code == 200) {
            this.$message.success('新建成功')
            this.addVisible = false
            this.getProudctModelingList()
          } else {
            this.$message.error('物料不能为空，请选择物料！')
          }
        } else {
          this.$message.error('请完善信息')
        }
        this.productModelingDetail = []
      })
    },
    closeAdd () {
      this.$refs.productModelAddRef.resetFields()
      this.getProudctModelingList()
      this.addVisible = false
      this.productModelingDetail = []
    },

    // 删除
    handleDelete (row) {  //删除（后端没实现）
    }
  }
}
</script>